package com.advanced.collectionAndGeneric_1;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * UpdateArrayList--案例 2 里，已经使用 ArrayList 存储了学员的信息，
 * 现在实现修改学员信息，根据输入的学号来进行修改(存入的学号是唯一的)，
 * 修改后将最新的学员信息输出，如图-1。.如果 没有该学员则提示信息，如图-2。
 *
 * @author: Jovi
 * @createTime: 2017-05-17 14:29
 **/
public class UpdateArrayList {

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        Student s1 = new Student(1, "房祖名", 12);
        Student s2 = new Student(2, "张三", 13);
        Student s3 = new Student(3,"李四",13);
        Student s4 = new Student(4,"王五",14);
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要修改的学员学号：");
        int id = sc.nextInt();
        int index = getIndex(students, id);
        if (index >= 0) {

            System.out.println("请输入要修改的学员姓名：");
            String name = sc.next();
            System.out.println("请输入要修改的学员年龄：");
            int age = sc.nextInt();
            students.get(index).setAge(age);
            students.get(index).setName(name);
            System.out.println("修改成功!");
            System.out.println("学员的信息如下：\n学号\t姓名\t年龄");
            for (Student stu : students) {
                System.out.println(stu.getId()+"\t"+stu.getName()+"\t"+stu.getAge());
            }
        } else {
            System.out.println("对不起，没有此学员！");

        }

    }

    public static int getIndex(ArrayList<Student> list, int id) {
        int index =-1;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == id) {
                index = i;
                break;
            }
        }
        return index;
    }
}
